/**
 *  初始化地区电话号码区号
 */

;(function($) {
    var defaultOptions = {
        isChinese : true,
        url: 'api/v1/app/common/country-code',
    };

    function DialCode( element, options ) {
        this.$el = $(element);
        this.$wrapper = null;
        this.options = $.extend( defaultOptions, options, true );
        this.$el.prop('readonly', true);
        this.$el.addClass('dial-code-picker');
        $plus = $('<span class="dial-code-plus">+</span>');
        $plus.css({
            lineHeight: this.$el.css('height'),
            height: this.$el.css('height'),
            textIndent: '8px',
        });
        this.$el.before($plus);
        this.initDialCode();
    }

    /**
     * 初始化
     */
    DialCode.prototype.initDialCode = function () {
        var url = this.options.isChinese? this.options.url : this.options.url+'?language=en-gb';
        this.fetchDialData(url, function (data) {
             this.setDefaultValue(data.default_country_code);
             this.$wrapper = this.renderUi(data);
             this.setProps();
             this.bindEvents();
             this.mount();
        }.bind(this), this.alert)
    };

    /**
     * 设置默认值
     * @param default_code
     */
    DialCode.prototype.setDefaultValue = function(default_code){
        this.$el.val(default_code)
    };

    /**
     * 绑定事件
     */
    DialCode.prototype.bindEvents = function(){
        var self = this;

        this.$wrapper.click(function (event) {
            self.$wrapper.hide();
            var code = event.target.dataset.code;
            self.$el.val(code);
        });

        this.$el.on('focus', function (event) {
            event.stopPropagation();
            self.setProps();
            self.$wrapper.show();
        });

        $(document).on('click', function (event) {

            if (!self.$el.is(event.target)){
                self.$wrapper.hide();
            }

        })
    };

    /**
     * 设置元素属性
     */
    DialCode.prototype.setProps = function() {
        var offsetTop = this.$el.offset().top + this.$el.outerHeight() +'px';
        var offsetLefgt = this.$el.offset().left + 'px';
        this.$wrapper.css({
            'top': offsetTop,
            'left': offsetLefgt
        });
    };

    /**
     *  插入元素
     */
    DialCode.prototype.mount = function(){
        $('body').append(this.$wrapper);
    };

    /**
     *  渲染UI
     */
    DialCode.prototype.renderUi = function (data) {
        var isChinese = this.options.isChinese;
        var text = $.map(data.country_codes, function (item) {
            if (isChinese) {
                return '<li data-code=\"'+item.dial_code+'\" >'+item.cn_name+ "+" +item.dial_code +'</li>';
            } else {
                return '<li data-code=\"'+item.dial_code+'\">'+item.country+ "+" +item.dial_code +'</li>';
            }
        }).join('');
        return $('<ul class="dial-code-wrapper">'+text+'</ul>')
    };

    /**
     * 请求区号数据
     * @param url
     * @param successCallback
     * @param errorCallback
     */
    DialCode.prototype.fetchDialData = function(url, successCallback, errorCallback) {
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'json',
            success: function(response) {
                if(response.code !== 0) {
                    errorCallback.call(null, new Error(response.error))
                }else {
                    successCallback.call(null, response);
                }
            },
            error: function (error) {
                errorCallback.call(null, error)
            }
        });
    };

    /**
     * 报错
     * @param error
     */
    DialCode.prototype.alert = function(error) {
        layer.open({
            skin: 'layer-alert',
            btnAlign: 'c',
            title: ' ',
            content: error.message || error.statusText
        });
    };


    // 绑定插件
    $.fn.dialCode = function( options ) {
        return this.each( function(item) {
            $(item).data('dial-code', new DialCode(this, options));
        } );
    }
})(window.jQuery);



